// app/middleware/jwt_auth_middleware.js
'use strict';

module.exports = (options, app) => {
  return async function jwtAuthMiddleware(ctx, next) {
    // 跳过插件数据接收接口，这些接口应该是公开的
    if (ctx.path.startsWith('/api/v1/plugin/data/receive')) {
      await next();
      return;
    }
    
    const token = ctx.headers.authorization;
    
    // 添加调试信息
    console.log('收到请求，token:', token);
    
    if (!token) {
      // 没有token，继续执行但不设置用户信息
      console.log('没有token，继续执行');
      await next();
      return;
    }
    
    try {
      // 验证JWT令牌
      const decoded = app.jwt.verify(token.replace('Bearer ', ''), app.config.jwt.secret);
      console.log('解码后的用户信息:', decoded);
      
      // 从数据库获取用户的完整信息，确保包含role等信息
      if (decoded.user && decoded.user.id) {
        const user = await ctx.model.UserModel.findByPk(decoded.user.id);
        if (user) {
          ctx.state.user = {
            id: user.id,
            name: user.name,
            role: user.role,
            email: user.email
          };
        } else {
          ctx.state.user = decoded.user || decoded;
        }
      } else {
        ctx.state.user = decoded.user || decoded;
      }
      
      // 获取用户所属的组织
      if (ctx.state.user.id) {
        const userOrganizations = await ctx.model.UserOrganizationModel.findAll({
          where: { userId: ctx.state.user.id, status: 'active' },
          include: [{
            model: ctx.model.OrganizationModel,
            as: 'organization'
          }]
        });
        
        ctx.state.userOrganizations = userOrganizations.map(uo => uo.organization);
        // 修复：应该从userOrganization对象本身获取organizationId字段
        ctx.state.user.organizationId = userOrganizations.length > 0 ? userOrganizations[0].organizationId : null;
        
        // 如果没有organizationId，尝试从关联的组织对象获取
        if (!ctx.state.user.organizationId && userOrganizations.length > 0 && userOrganizations[0].organization) {
          ctx.state.user.organizationId = userOrganizations[0].organization.id;
        }
      }
      
      await next();
    } catch (error) {
      console.error('token验证失败:', error);
      // 特别处理JWT过期错误
      if (error.name === 'TokenExpiredError') {
        console.log('JWT token已过期');
        // 可以选择返回特定的错误响应或继续执行
        ctx.status = 401;
        ctx.body = {
          code: 401,
          message: '登录已过期，请重新登录',
          data: null
        };
        return;
      }
      // token验证失败，继续执行但不设置用户信息
      await next();
    }
  };
};